package a07_二叉树;

/**
 * <p>
 * a14_从中序与后序遍历序列构造二叉树
 * </p>
 *
 * @author flyduck
 * @since 2024-09-10
 */
public class a18_从中序与后序遍历序列构造二叉树复习1 {

    public static void main(String[] args) {
        int[] inorder = {9,3,15,20,7};
        int[] postorder = {9,15,7,20,3};
        a18_从中序与后序遍历序列构造二叉树复习1 test = new a18_从中序与后序遍历序列构造二叉树复习1();
        TreeNode treeNode = test.buildTree(inorder, postorder);
        System.out.println();
    }

    //inorder = [9,3,15,20,7],   左中右
    // postorder = [9,15,7,20,3] 左右中

    //1、取出
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        //中止条件
        if(postorder.length == 0){
            return null;
        }
        if(postorder.length == 1){
            return new TreeNode(postorder[0]);
        }

        //1、用后序最后切割中序
        int rootValue = postorder[postorder.length - 1];
        TreeNode rootNode = new TreeNode(rootValue);

        int rootIdx = 0;
        for (int i = 0; i < inorder.length; i++) {
            if(inorder[i] == rootValue){
                rootIdx = i;
                break;
            }
        }

        int[] leftInorder = spiltArray(inorder, 0, rootIdx - 1);
        int[] rightInorder = spiltArray(inorder, rootIdx + 1, inorder.length - 1);

        int[] leftPostorder = spiltArray(postorder, 0, leftInorder.length - 1);
        int[] rightPostorder = spiltArray(postorder, leftInorder.length, postorder.length - 2);

        rootNode.left = buildTree(leftInorder, leftPostorder);
        rootNode.right = buildTree(rightInorder, rightPostorder);
        return rootNode;
    }

    public int[] spiltArray(int[] oldArray,int leftIdx,int rightIdx){
        int[] newArray = new int[rightIdx - leftIdx + 1];
        for (int i = 0; i < newArray.length; i++) {
            newArray[i] = oldArray[leftIdx];
            leftIdx++;
        }
        return newArray;
    }





}
